package com.verio.controller;

import com.verio.dto.Resp;
import com.verio.dto.RespResult;
import com.verio.entity.Contract;
import com.verio.entity.Room;
import com.verio.entity.RoomOrder;
import com.verio.entity.User;
import com.verio.utils.Assert;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "contract")
public class ContractController extends BaseController<Contract>{
    @PostMapping("/saveContract")
    @ResponseBody
    public String saveContract(Integer orderId) {
        RoomOrder roomOrder = roomOrderService.get(orderId);

        Integer landlordId = roomOrder.getOwnerId();
        User landlord = userService.get(landlordId);
        String landlordName = landlord.getName();
        String landlordIdcard = landlord.getIdcardNum();

        Integer tenantId = roomOrder.getUserId();
        User tenant = userService.get(tenantId);
        String tenantName = tenant.getName();
        String tenantIdcard = tenant.getIdcardNum();

        Date rentalStartTime = roomOrder.getFromTime();
        Date rentalOutTime = roomOrder.getToTime();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String rentalStartTimeStr = simpleDateFormat.format(rentalStartTime);
        String rentalOutTimeStr = simpleDateFormat.format(rentalOutTime);

        Double price = roomOrder.getPayMoney();

        Integer roomId = roomOrder.getRoomId();
        String address = roomService.get(roomId).getLocation();
        Date payDay = roomOrder.getPayTime();
        Date createTime = roomOrder.getCreateTime();
        Date updateTime = roomOrder.getUpdateTime();


        Contract contract = Contract.builder()
                .landlord(landlordName)
                .landlordIdcard(landlordIdcard)
                .tenant(tenantName)
                .tenantIdcard(tenantIdcard)
                .rentalStartTime(rentalStartTimeStr)
                .rentalOutTime(rentalOutTimeStr)
                .price(new BigDecimal(price.toString()))
                .address(address)
                .roomId(roomId)
                .payday(payDay)
                .status(1)
                .createTime(createTime)
                .updateTime(updateTime)
                .build();

        Contract save = contractService.save(contract);
        if (Assert.isEmpty(save)) {
            return Resp.resp(RespResult.fail("合同签订失败"));
        }
        return Resp.resp(RespResult.success("合同签订成功"));
    }
}
